package com.ews.onlineexchange.controller;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.primefaces.model.StreamedContent;

import com.ews.onlineexchange.app.entity.BulletinStat;
import com.ews.onlineexchange.app.entity.ServiceBuyerStat;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.service.BulletinService;
import com.ews.onlineexchange.service.QualificationClassService;
import com.ews.onlineexchange.service.ServiceBuyerService;
import com.ews.onlineexchange.service.ServiceSupplierService;
import com.ews.onlineexchange.util.WorkBookUtil;

@ViewScoped
@Named
public class StatExport implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String EXPORT_DATA_ERROR_TIP = "导出数据出错，请稍后重试！";

	public static String[] FIELD_LABELS_SUPPIER_FIRST_ROW = {"中介机构","报名次数","中选次数"};
	public static String[] FIELD_LABELS_SUPPIER_SECOND_ROW = {"合计","随机选取","择优选取","竞价选取","均价选取","评审选取","直接选取"};//第三列开始
	public static String[] FIELD_NAMES_SUPPLIER = {"cnname","appliedCount","successCount","randomSuccessCount","bestSuccessCount","priceSuccessCount","averageSuccessCount","assessSuccessCount","manualSuccessCount"};
	public static String[] FIELD_NAMES_BUYER = {"buyerName","bulletinCount","totalPrice","appliedCount"};
	public static String[] FIELD_LABEL_BUYER = {"采购方","发布公告数","累计成交金额（元）","参与报名数"};
	public static String[] FIELD_NAMES_BULLETIN = {"dataStr","count","priceCount","appliedCount"};
	public static String[] FIELD_LABEL_BULLETIN = {"月份","累计公告数","累计成交金额（元）","参与报名数"};
	public static String[] FIELD_NAMES_QCLASS = {"dataStr","count","priceCount","appliedCount"};
	public static String[] FIELD_LABEL_QCLASS = {"资质类型","累计公告数","累计成交金额（元）","参与报名数"};
	
	private Date startDate;
	private Date endDate;
	private Integer year;
	@Inject
	ServiceSupplierService  serviceSupplierService;
	@Inject
	ServiceBuyerService  serviceBuyerService;
	public StreamedContent suppierStatExport(){	
		List<ServiceSupplier> suppliers = (List<ServiceSupplier>)serviceSupplierService.stat(null, 1, null, null, null, null, null).get("list")	;		
		HSSFWorkbook workbook = statExportForSupplier("按中介机构统计",2,suppliers,true,null,FIELD_NAMES_SUPPLIER);	
		return WorkBookUtil.getSteamedContentByWorkBook("按中介机构统计.xls", workbook);
	}
	
	public StreamedContent buyerStatExport(){	
		List<ServiceBuyerStat> suppliers = (List<ServiceBuyerStat>)serviceBuyerService.stat(null, 1, null, null, null).get("list")	;		
		HSSFWorkbook workbook = statExportForSupplier("按采购方统计",1,suppliers,false,FIELD_LABEL_BUYER,FIELD_NAMES_BUYER);		
		return WorkBookUtil.getSteamedContentByWorkBook("按采购方统计.xls", workbook);
	}
	@Inject
	BulletinService bulletinService;
	public StreamedContent bulletinStatExport(){	
		List<BulletinStat> stats = (List<BulletinStat>)bulletinService.bulletinStat(2019, null);		
		HSSFWorkbook workbook = statExportForSupplier("按月份统计",1,stats,false,FIELD_LABEL_BULLETIN,FIELD_NAMES_BULLETIN);		
		return WorkBookUtil.getSteamedContentByWorkBook("按月份统计.xls", workbook);
	}
	
	@Inject
	QualificationClassService qualificationClassService;
	public StreamedContent qualificationClassStatExport(){	
		List<BulletinStat> stats = (List<BulletinStat>)qualificationClassService.QualificationStat(null, null);		
		HSSFWorkbook workbook = statExportForSupplier("按资质类型统计",1,stats,false,FIELD_LABEL_QCLASS,FIELD_NAMES_QCLASS);		
		return WorkBookUtil.getSteamedContentByWorkBook("按资质类型统计.xls", workbook);
	}
	
	public static HSSFWorkbook statExportForSupplier(String sheetName,int rowIndex,List list,boolean merge,String[] FIELD_LABEL_ARRAY,String[] FIELD_NAME_ARRAY) {
		WorkBookUtil workbookUtil = new WorkBookUtil();
		HSSFWorkbook workbook = null;
		try {
			if(merge)workbook = workbookUtil.createWorkbookMergingCell(sheetName,FIELD_LABELS_SUPPIER_FIRST_ROW, FIELD_LABELS_SUPPIER_SECOND_ROW, 0, 2);
			else workbook = workbookUtil.createWorkbook(sheetName, FIELD_LABEL_ARRAY);
			HSSFSheet sheet =  workbook.getSheetAt(0);
			for(int i = 0; i < list.size() ; i++) {
				Object object = list.get(i);
				HSSFRow row = sheet.createRow(i + rowIndex);
				for(int j = 0;j < FIELD_NAME_ARRAY.length ; j++) {
					HSSFCell cell = row.createCell(j);
					String fieldValue = "";
					fieldValue= BeanUtils.getProperty(object, FIELD_NAME_ARRAY[j]);
					cell.setCellValue(fieldValue);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,StatExport.EXPORT_DATA_ERROR_TIP,"");
	        FacesContext.getCurrentInstance().addMessage(null, message);
	        return null;
		}
		return workbook;
	}
	public Date getStartDate() {
		return startDate;
	}
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}
	public Date getEndDate() {
		return endDate;
	}
	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
	public Integer getYear() {
		return year;
	}
	public void setYear(Integer year) {
		this.year = year;
	}
	
	
}
